package org.xnat.xnatfs.asset;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;

public class HttpResponseStringAsset extends HttpResponseAsset implements IStringAsset {
  private String content;

  public HttpResponseStringAsset ( HttpResponse response ) throws IOException {
    super ( response );
    if ( getEntity () != null ) {
      try {
        content = convertToString ( getEntity ().getContent () );
      } finally {
        // release the resource
        close ();
      }
    }
  }

  @Override
  public String getContent () {
    return content;
  }

  private String convertToString ( InputStream is ) throws IOException {
    StringBuilder sb = new StringBuilder ();
    int c;
    char buffer[] = new char[1024];
    try {
      InputStreamReader reader = new InputStreamReader ( is );
      while ( ( c = reader.read ( buffer, 0, 1024 ) ) != -1 ) {
        sb.append ( new String ( buffer, 0, c ) );
      }
    } finally {
      is.close ();
    }
    return sb.toString ();
  }
}
